package com.easydev.mq.rabbit.listener;

import java.io.IOException;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.rabbitmq.client.Channel;

/**
 * <Description> 简单广播消息订阅，用于基于订阅/发布模式订阅消息（Pub/Sub）<br>
 * 
 * @author lx<br>
 * @version 1.0<br>
 * @CreateDate 2016年3月16日 <br>
 */
public abstract class RabbitTopicMessageListener extends RabbitMessageListener {
    private final static Logger LOGGER = LoggerFactory.getLogger(RabbitMessageListener.class);

    public RabbitTopicMessageListener(String topic) throws Exception {
        prepare(topic, "");
    }

    public RabbitTopicMessageListener(String topic, String virtualHost) throws Exception {
        prepare(topic, virtualHost);
    }

    private void prepare(String topic, String virtualHost) throws Exception, IOException {
        Channel channel = channelPool.borrowObject(virtualHost);
        // 创建一个非持久化、独立的、自动删除的队列，且名字是随机生成的
        String queue = channel.queueDeclare().getQueue();
        channel.queueBind(queue, topic, StringUtils.EMPTY);
        dealMessage(queue, channel);
    }

    @Override
    public abstract void handleMessage(String message) throws Exception;

    @Override
    public void handleFailedMessage(String message) {
        LOGGER.error("deal message failed,message is " + message);
    }

}
